<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->helper('file');
		$this->load->helper('url');
	}

	public function index($page = "")
	{


		$data = $this->_check_page($page);
		// в будущем программа должна отображать кастомную 404 страницу
		if ($data['ret'] == false || $data['active'] == 'false')
		{
			show_404($page);
			exit;
		}

		$this->load->library('Smartyclass');

		//$smarty->debugging = true;
		//$smarty->force_compile = true;
		$smarty = $this->smartyclass->smarty;

		$smarty->assign('PAGE', $data['real_name']);
		$smarty->assign('NAME', $data['mname']);
		$smarty->assign('TITLE', $data['title']);
		$smarty->assign('DESCRIPTION', $data['description']);
		$smarty->assign('KEYWORDS', $data['keywords']);
		$smarty->assign('PARAMS', $data['params']);
		$smarty->assign('PATH', $data['path']);

		if ($data['cached'] == 'true' && $data['cache_time'] > 0)
		{
			// sets cache params for smarty
			$smarty->setCaching(Smarty::CACHING_LIFETIME_SAVED);
			$smarty->setCacheLifetime($data['cache_time']);

			// пока эти переменные не будем использовать, оставим для будущего
			$smarty->assign('TTL',		$data['cache_time']);
			//$smarty->assign('EXPIRED',	gmstrftime("%a, %d %b %Y %T %Z", time()+$data['cache_time']);

		}
		else
		{
			$smarty->assign('TTL',		0);
		}

		// wants debug? no problem
		if ($data['enable_debug'] == 'true')
		{
			$smarty->debugging = true;
		}

		$smarty->display('page#'.$data['real_name'], $data['path'][count($data['path'])-1]['link']);


	}

	public function _remap($method, $params = array())
	{

		//print_r ($this->uri->segments);
		$page = "";
		foreach ($this->uri->segments as $subpage)
		{
			if ($page != "")
				$page .= "/";
			$page .= urldecode ($subpage);
		}
		if ($page == '') $page = 'index';
		$this->index($page);

	}

	private function _check_page (&$name)
	{
		$data = array();
		$parent_id = 0;
		$names = explode ('/', $name);
		$real_name = "";
		$i = 0;
		$ret = false;
		$path = array ();
		foreach ($names as $n)
		{
			$this->db->where('parent_id', $parent_id);
			$this->db->where('name', $n);
			$this->db->select('id, parent_id, name, title, description, keywords, mname, active, max_num_params, cached, cache_time, enable_debug');
			$query = $this->db->get('foria_pages');
			if ($row = $query->result_array())
			{
				$parent_id = $row[0]['id'];
				if ($real_name!="") $real_name .= '/';
				$real_name .= $row[0]['name'];
				$path[] = array (
					'name'=>$row[0]['name'],
					'mname'=>$row[0]['mname']==""?$row[0]['name']:$row[0]['mname'],
					'link' => $real_name,
					'is_last'=>false
				);
				$data = $row[0];
				$i++;
			}
		}

		/*
		 * Если максимальное количество параметров больше допустимого
		 * то показываем 404
		 */
		if ($i == 0 || count($names) -$i > $data['max_num_params']) {
			show_404($real_name);
			exit;
		}

		if ($i > 0) $ret = true;

		$data['params'] = array();
		$l = $real_name;

		for ($i; $i<count($names); $i ++)
		{
			$p = html_entity_decode($names[$i], ENT_COMPAT, 'UTF-8');
			$l .= '/'.$p;
			$path[]= array ('name'=>$p, 'mname'=>$p, 'is_last' => false, 'link' => $l);
			$data['params'][] = $p;
		}

		if (count($path)>0)
		{
			$path[count($path)-1]['is_last']=true;
		}

		$data['path']= $path;


		// kjопределим параментры по умолчанию
		// и будем считать что их может быть всего 10
		for ($n = count($names); $n<10; $n ++)
		{
			$data['params'][] = '';
		}

		$data ['real_name'] = $real_name;
		$data ['ret'] = $ret;

		return $data;

	}


}
